from django_filters.rest_framework import DjangoFilterBackend

from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from rest_framework.filters import OrderingFilter
from rest_framework import status
from rest_framework.response import Response

from XApiTestServer.models import TestConfig
from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import ConfigSerializer, ConfigSumSerializer
from XApiTestServer.utils.response import *
from XApiTestServer.utils.convertor import *
from XApiTestServer.utils.auth import get_username

import logging


logger = logging.getLogger('XApiTestServer')


class ConfigViewSet(viewsets.ModelViewSet):
    queryset = TestConfig.objects.all()
    serializer_class = ConfigSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('name',)
    filterset_fields = ('belong_project',)
    ordering_fields = ('update_time',)

    def _name_validator(self, project_id, config_name, config_id=None):
        if config_id: # update
            actualname = TestConfig.objects.filter(id=config_id).values('name')
            if actualname[0]['name'] == config_name:
                return False
            else:
                configlist = TestConfig.objects.filter(belong_project=project_id).values('name')
                for a in configlist:
                    if a['name'] == config_name:
                        return True
                    else:
                        continue
                return False
        else: # create
            configlist = TestConfig.objects.filter(belong_project=project_id).values('name')
            for a in configlist:
                if a['name'] == config_name:
                    return True
                else:
                    continue
            return False

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_body = SUCCESS_INFO
        response_body['data'] = serializer.data
        response_body['data']['config_body'] = db_config_body_to_vue(response_body['data']['config_body'])
        print(response_body['data']['config_body'])
        return Response(response_body)

    def create(self, request, *args, **kwargs):
        if not request.data['belong_project']:
            msg = '项目不能为空'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if request.data['config_body']['url']['base_url']:
            import validators
            if not validators.url(request.data['config_body']['url']['base_url']):
                msg = 'base_url不是合法的完整url'
                return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)
        else:
            msg = 'base_url为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if request.data.get('config_body').get('database'):
            request.data['config_body']['database'] = \
                vue_to_db_list('database', request.data.get('config_body').get('database'))

        if request.data.get('config_body').get('variables'):
            request.data['config_body']['variables'] = \
                vue_to_db_list('variables', request.data.get('config_body').get('variables'))
        request.data['config_body'] = str(request.data['config_body'])

        token = request.META.get("HTTP_X_TOKEN", None)
        username=get_username(token)
        request.data['author'] = username

        if self._name_validator(request.data['belong_project'], request.data['name']):
            return Response(CONFIG_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            response_body = SUCCESS_ADD
            response_body['data'] = serializer.data
            return Response(response_body, status=status.HTTP_201_CREATED, headers=headers)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        if not request.data['belong_project']:
            msg = '项目不能为空'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if request.data['config_body']['url']['base_url']:
            import validators
            if not validators.url(request.data['config_body']['url']['base_url']):
                msg = 'base_url不是合法的完整url'
                return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)
        else:
            msg = 'base_url为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if request.data.get('config_body').get('database'):
            request.data['config_body']['database'] = \
                vue_to_db_list('database', request.data.get('config_body').get('database'))

        if request.data.get('config_body').get('variables'):
            request.data['config_body']['variables'] = \
                vue_to_db_list('variables', request.data.get('config_body').get('variables'))

        request.data['config_body'] = str(request.data['config_body'])

        token = request.META.get("HTTP_X_TOKEN", None)
        username=get_username(token)
        request.data['author'] = username

        if self._name_validator(request.data['belong_project'], request.data['name'], request.data['id']):
            return Response(CONFIG_EXISTS, status=status.HTTP_201_CREATED)

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            # serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)

            response_body = SUCCESS_UPDATE
            response_body['data'] = serializer.data
            return Response(response_body)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        response_body = SUCCESS_DEL
        return Response(response_body)

class ConfigSumViewSet(viewsets.ModelViewSet):
    queryset = TestConfig.objects.all()
    serializer_class = ConfigSumSerializer
    search_fields = ('name',)
    filterset_fields = ('belong_project',)
    ordering_fields = ('update_time',)

    def list(self, request, *args, **kwargs):
        belong_project = request.GET.get('belong_project', '')
        if belong_project:
            queryset = TestConfig.objects.filter(belong_project=belong_project)
        else:
            queryset = TestConfig.objects.all()
        serializer = self.get_serializer(queryset, many=True)

        response_body = SUCCESS_LIST
        response_body['results'] = serializer.data

        return Response(response_body)
